package com.simple.demo.desginModel.observer;

import java.util.ArrayList;
import java.util.List;

/**
 * 被观察者对象
 */
public class ObserverManager implements  Subject {

    private String userName;

    private String time;

    private String msg;

    /**
     * 定义观察者列表
     */
    List<Observer> observerList = new ArrayList<>();

    @Override
    public void addObserver(Observer observer) {
        removeObserver(observer);
        observerList.add(observer);
    }

    @Override
    public void removeObserver(Observer observer) {

        int i = observerList.indexOf(observer);
        if(i > 0 ){
            observerList.remove(i);
        }
    }

    @Override
    public void notifyObservers() {
        observerList.forEach(item ->{
            item.update(userName,time,msg);
        });
    }

    /**
     * 被观察者数据发生改变
     * @param userName
     * @param time
     * @param msg
     */
    @Override
    public void changeOfObjserver(String userName,String time,String msg){
     this.userName=userName;
     this.time = time;
     this.msg= msg;
     notifyObservers();
    }
}
